package com.obrempon.credit.market.ui.activity

import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.obrempon.credit.market.R
import com.obrempon.credit.market.common.CommonActivity
import com.obrempon.credit.market.databinding.ObremponUserProfileActBinding
import com.obrempon.credit.market.event.ObremponEventData
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.httptest.api.UpdateImageApi
import com.obrempon.credit.market.request.HttpHelper
import com.obrempon.credit.market.utils.ObremponImageUtil
import com.obrempon.credit.market.utils.ObremponTitleBarUtil
import com.obrempon.credit.market.utils.helper.ObremponCustomDataHelper
import com.obrempon.credit.market.utils.imgcovert.ImageConvert
import com.obrempon.credit.market.utils.log.ObremponLogger
import com.obrempon.module.easyhttp.config.IRequestApi
import com.obrempon.module.easyhttp.listener.OnUpdateListener
import com.obrempon.module.shapeview.drawable.ShapeGradientOrientation

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/28 18:11
 * @Annotation：个人信息
 */
class ObremponUserProfileAct: CommonActivity(){
    lateinit var binding: ObremponUserProfileActBinding
    //图片选择
    lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    override fun takeObremponRootView(): View {
        binding = ObremponUserProfileActBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initObremponView() {
        setObremponTitleBarVisibility(View.VISIBLE)
        setObremponTextTitle(getString(R.string.obrempon_user_center_profile))
        setObremponTextTitleColor(getColor(R.color.black))
        setObremponRightBtnRes(R.mipmap.obrempon_customer_icon)
        setObremponBackBtnRes(R.mipmap.obrempon_back_icon)
        ObremponTitleBarUtil.setStatusBarLightMode(this, true)
        setObremponTitleBarVisibility(View.VISIBLE)
        rootViewBinding.rootLayout.shapeDrawableBuilder
            .setSolidGradientColors(getColor(R.color.color_ffcbe0ff),getColor(R.color.white),getColor(R.color.white))
            .setSolidGradientOrientation(ShapeGradientOrientation.TOP_TO_BOTTOM)
            .intoBackground()
    }

    override fun initObremponListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Profile Page")
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_CUSTOMER,"Profile Page")
            if (binding.editUserName.isFocused){
                binding.editUserName.clearFocus()
            }
        }
        binding.parentLayout.setOnClickListener {
            if (binding.editUserName.isFocused){
                binding.editUserName.clearFocus()
            }
        }
        binding.imgUserPicture.setOnClickListener {
            if (binding.editUserName.isFocused){
                binding.editUserName.clearFocus()
            }
            openUserInfoAlbum()
        }
        //昵称
        binding.editUserName.setOnFocusChangeListener { v, hasFocus ->
            when(hasFocus){
                true -> {//获得焦点
                }
                else -> {//失去焦点
                    val userName = binding.editUserName.text.toString().trim()
                    if (userName.isNotEmpty()){
                        ObremponCustomDataHelper.saveObremponCustomUserNameAction(userName)
                    }
                }
            }
        }

        binding.editUserName.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editUserName.clearFocus()
                true
            }
            false
        }

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        ObremponLogger.e(">>>>>>>album>>>>>>>>>>$localPath")
                        uploadObremponImageAction(localPath)
                    }
                }
            } else {
                ObremponLogger.e("No media selected")
            }
        }
    }

    override fun takeObremponData() {
        setUserInfoData()
    }

    /**
     * 设置用户信息
     */
    private fun setUserInfoData(){
        val avatarUrl = ObremponCustomDataHelper.queryObremponCustomUserAvatarUrl()
        if (avatarUrl.isNotEmpty()){
            ObremponImageUtil.instance.loadImageUrl(this,binding.imgUserPicture,avatarUrl)
        } else {
            binding.imgUserPicture.setImageResource(R.mipmap.obrempon_holder)
        }
        binding.editUserName.setText(ObremponCustomDataHelper.queryObremponCustomUserName())
    }

    /**
     * 打开相册
     */
    private fun openUserInfoAlbum(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 图片上传成功
     */
    fun showObremponUploadImageSuccess(imgPath: String, imgUrl: String) {
        ObremponImageUtil.instance.loadImageUrl(this,binding.imgUserPicture,imgPath)
        ObremponCustomDataHelper.saveObremponCustomUserAvatar(imgUrl)
    }

    override fun onObremponPublishEvent(event: ObremponEventData) {
        super.onObremponPublishEvent(event)
        when(event.eventType){
            ObremponEventData.TYPE.OBREMPON_CUSTOM_DATA_REFRESHED -> {//自定义数据刷新完成
                //设置用户昵称和头像
                setUserInfoData()
            }
            else -> {

            }
        }
    }

    /**
     * 图片上传
     */
    private fun uploadObremponImageAction(imgPath: String){
        showObremponLoading(isTOuchOut = false, isCancel = false)
        HttpHelper.setTag(this)
        HttpHelper.upload(imgPath,object : OnUpdateListener<UpdateImageApi.ImageBean> {
            override fun onUpdateProgressChange(progress: Int) {
                ObremponLogger.e(">onUpdateProgressChange>>>>>>>>>>>>>>>>$progress")
            }

            override fun onUpdateFail(throwable: Throwable) {
                ObremponLogger.e(">throwable>>>>>>>>>>>>>>>>")
            }

            override fun onUpdateSuccess(result: UpdateImageApi.ImageBean) {
                ObremponLogger.e(">onUpdateSuccess>>>>>>>>>>>>>>>>${result.obj.url}")
                when(result.code){
                    0 -> {
                        val imgUrl = result.obj.url
                        showObremponUploadImageSuccess(imgPath,imgUrl)
                    }
                    else -> {
                        showObremponToast(result.msg)
                    }
                }
            }

            override fun onUpdateEnd(api: IRequestApi) {
                ObremponLogger.e(">onUpdateEnd>>>>>>>>>>>>>>>>")
                hideObremponLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_USER_INFORMATION_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_USER_INFORMATION_END)
    }
}